﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace CRC
{
    public partial class usrFoto : UserControl
    {
        MySql.Data.MySqlClient.MySqlDataAdapter ad;
        DataAccess bd = new DataAccess();
        DataSet ds = new DataSet();
        private string strId = "";
        private int cTb=-1;
        private UsrThumbnail[] tB;
        PictureBox tmpPic;

        public usrFoto()
        {
            InitializeComponent();

            if (strId != string.Empty)
            {
                Cargar_Carpetas(); // Cargo las carpetas contenedoras de imagenes.  
            }
        }

        private void Cargar_Carpetas()
        {

            //Limpio la tabla FotoFiles, del Dataset ( try para el caso de q no se haya creado.)
            try { ds.Tables["fCat"].Clear(); }
            catch { }       
           
            bd.Init();
            listView1.Clear();

            string strSQL = "SELECT * FROM cat_archivos WHERE Visible = 1 AND GRUPO = '0001000' ORDER BY Categoria";

            ad = bd.LoadData(strSQL);
            ad.Fill(ds, "fCat");

            for (int i = 0; i <= ds.Tables["fCat"].Rows.Count - 1; i++)
            {
               // nnnn = ds.Tables["fCat"].Rows[i]["Categoria"].ToString();
               // lstV.Items.Add(ds.Tables["fCat"].Rows[i]["Categoria"].ToString(), ds.Tables["fCat"].Rows[i]["Nombre"].ToString(),2);
                listView1.Items.Add(ds.Tables["fCat"].Rows[i]["Categoria"].ToString(), ds.Tables["fCat"].Rows[i]["Nombre"].ToString(),0);
            }

            //ad.Dispose();

            Application.DoEvents();
            System.Threading.Thread.Sleep(2000);
        }

        public void Cargar_Imagenes(string strCategoria)
        {
            Application.DoEvents();
            System.Threading.Thread.Sleep(2000);

            //Elimino las imagenes
            flPanel1.Controls.Clear();
            
            //Limpio el Dataset
            try { ds.Tables["fotoFiles"].Clear(); }
            catch { }

            //string strSQL = "SELECT * FROM salones_fotos WHERE ID_SALON = '1' ORDER BY CATEGORIA;";
            string strSQL = "SELECT id, file_name, file_size, categoria, id_salon, thumbnail, grupo, info FROM salones_fotos WHERE ID_SALON = '" + strId + "' AND GRUPO = '0001000' AND CATEGORIA = '" + strCategoria + "' ORDER BY CATEGORIA;";
                        
            bd.Init();
            ad = bd.LoadData(strSQL);
            ad.Fill(ds, "fotoFiles");

            Image image1;
            byte[] buffer;
            System.IO.MemoryStream stream1;

            //usrThumbnail[] tB = new usrThumbnail[ds.Tables["fotoFiles"].Rows.Count];
            //tB = new UsrThumbnail[ds.Tables["fotoFiles"].Rows.Count];

            for (int i = 0; i <= ds.Tables["fotoFiles"].Rows.Count - 1; i++)
            {
                //tB[i] = new UsrThumbnail();
                //tB[i].Thumbnail_BackColor = Color.WhiteSmoke;
                //tB[i].Visible = true;
                //tB[i].Nombre_Imagen = ds.Tables["fotoFiles"].Rows[i]["file_name"].ToString();
                //tB[i].Name = "Thb" + i.ToString();
                //tB[i].Index = i;
                //tB[i].Id = ds.Tables["fotoFiles"].Rows[i]["id"].ToString();
                //tB[i].Info = ds.Tables["fotoFiles"].Rows[i]["info"].ToString();
                //tB[i].FileSize = ds.Tables["fotoFiles"].Rows[i]["file_size"].ToString();
    
                //// Asociando eventos
                //tB[i].Borrar_Click += new CRC.UsrThumbnail.TBEventPickClik(this.Thumbnail_Borrar);
                //tB[i].Info_Click += new CRC.UsrThumbnail.TBEventPickClik(this.Thumbnail_Info);
                //tB[i].TbSelected += new CRC.UsrThumbnail.TBEventSelected(this.Thumbnail_Click);
                
                //this.cntBuscar1.CargarSalon += new crc.cntBuscar.EventLoadSalon(this.cntBuscar1_CargarSalon);
                
                //flPanel1.Controls.Add(tB[i]);
                Application.DoEvents();
                System.Threading.Thread.Sleep(2000);
            }

            Application.DoEvents();
            System.Threading.Thread.Sleep(2000);

            for (int i = 0; i <= ds.Tables["fotoFiles"].Rows.Count - 1; i++)
            {
                buffer = bd.getThumbnail(Convert.ToInt32(ds.Tables["fotoFiles"].Rows[i]["id"]), "salones_fotos");
                stream1 = new System.IO.MemoryStream(buffer, true);
                stream1.Write(buffer, 0, buffer.Length);

                try
                {
                    image1 = System.Drawing.Bitmap.FromStream(stream1, true);
                    tB[i].Imagen = image1;
                } catch { }              
                
        
                Application.DoEvents();
                System.Threading.Thread.Sleep(2000);
            }
            //ad.Dispose();
        }

        private void ThumbnailCallback()
        {
        }
        
        private void Thumbnail_Click(int Index)
        {
            //MessageBox.Show(Id.ToString());
            // Acción mostrar info 
            cTb = Index;      

            // Cargo la Imagen Buffer//Stream
            byte[] buffer;
            System.IO.MemoryStream stream1;

            buffer = bd.getImage(Convert.ToInt32(tB[Index].Id), "salones_fotos");
            stream1 = new System.IO.MemoryStream(buffer, true);
            stream1.Write(buffer, 0, buffer.Length);

            Image img;

            // Cargamos la imagen en el Control Picture                              
            img = System.Drawing.Bitmap.FromStream(stream1, true);
            
            // Asignamos aspecto de la imagen a mostrar
            tmpPic = new PictureBox();
            tmpPic.Image = img;
            tmpPic.BorderStyle = BorderStyle.FixedSingle;
            tmpPic.Height = flPanel1.Height;
            tmpPic.Width = flPanel1.Width;
            tmpPic.Top = 0; 
            tmpPic.Left = 0;
            tmpPic.SizeMode = PictureBoxSizeMode.Zoom;
            tmpPic.BackColor = Color.White;
            tmpPic.Show();
            
            //Incorporamos la imagen al panel principal
            splitContainer1.Panel1.Controls.Add(tmpPic);
            tmpPic.BringToFront();

            //Boton para cerrar/destruir la imagen.
            btnCerrar.Left = splitContainer1.Left + splitContainer1.Panel1.Width - btnCerrar.Width;
            btnCerrar.Top = 31 + btnCerrar.Height; 
            btnCerrar.Visible = true;
            
            // Cargamos la info de la imagen en el cuadro de texto
            txtInfo.Text = tB[Index].Info;
            lblSize.Text = "Tamaño: " + (Convert.ToString(Convert.ToInt32(tB[Index].FileSize) / 1024)) + " Kb";
            
            //if (ButtonPress == Convert.ToInt32(MouseButtons.Left)) { MessageBox.Show(ButtonPress.ToString()); }
        }

        private void Thumbnail_Info(int Index, int ButtonPress)
        {
            //MessageBox.Show(Id.ToString());
            // Acción mostrar info 
            cTb = Index;
           
            // if (ButtonPress == Convert.ToInt32(MouseButtons.Left)) { MessageBox.Show(ButtonPress.ToString()); }
            
            // Cargamos la info de la imagen en el txtInfo
            txtInfo.Text = tB[Index].Info;
            lblSize.Text = "Tamaño: " + (Convert.ToString(Convert.ToInt32(tB[Index].FileSize) / 1024)) + " Kb";

        }

        private void Thumbnail_Borrar(int Index, int ButtonPress)
        {
            cTb = Index;
            if (MessageBox.Show("¿Esta seguro de querer eliminar esta Imagen?", "Eliminar Imagen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                bd.Init();
                bd.Execute("DELETE FROM salones_fotos WHERE ID = " + tB[Index].Id.ToString() + ";");

                // Recargo las Imagenes
                Cargar_Imagenes(listView1.SelectedItems[0].Name.ToString());
            }

        }
        



        private void btnAddFolder_Click(object sender, EventArgs e)
        {

            bd.Init();

            string strSQL = "SELECT Categoria FROM cat_archivos WHERE GRUPO = '0001000' ORDER BY Categoria";

            ad = bd.LoadData(strSQL);
            ad.Fill(ds, "cCat");
            
            string vAc = ""; // Valor Actual
            int vAn = 1000;  // Valor Anterior

            // Recorro Bucles en busca de huecos o categorias borradas que pueda aprovechar
            for (int i=0; i < ds.Tables["cCat"].Rows.Count; i++)
            {
                //MessageBox.Show(ds.Tables["cCat"].Rows[i][0].ToString());
                if (vAn + 1 < Convert.ToInt32(ds.Tables["cCat"].Rows[i][0]))
                {
                    vAc = (vAn + 1).ToString().PadLeft(7,'0');                
                }
                vAn = Convert.ToInt32(ds.Tables["cCat"].Rows[i][0]);

                if (vAc != String.Empty)
                {
                    // Salimos del bucle (ya tenemos nuestra categoría);
                    i = ds.Tables["cCat"].Rows.Count;
                }
            }

            if (vAc == String.Empty)
            {
                vAc = (vAn+1).ToString().PadLeft(7, '0');
            }
         
            bd.Init();
            bd.Execute("INSERT INTO cat_archivos (CATEGORIA, NOMBRE,VISIBLE, GRUPO) VALUES ('" + vAc + "', 'Carpeta " + vAc + "',1,'0001000');");

            //Limpio el dataset para la proxima busqueda
            ds.Tables["cCat"].Clear();
            
            //ad.Dispose();

            // Recargo el listview
            Cargar_Carpetas();
        }

        private void btnDelFolder_Click(object sender, EventArgs e)
        {
            bd.Init();

            if (listView1.SelectedItems.Count != 0)
            {
                if (MessageBox.Show("¿Esta seguro de querer eliminar el registro?", "Eliminar registro", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    bd.Execute("DELETE FROM cat_archivos WHERE CATEGORIA = '" + listView1.SelectedItems[0].Name.ToString() + "' AND GRUPO = '0001000';");

                    // Recargo el listview
                    Cargar_Carpetas();
                }
            }
            else
            { 
                MessageBox.Show("Seleccione primero una carpeta", "Eliminar carpeta", MessageBoxButtons.YesNo, MessageBoxIcon.Information); 
            }

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Limpio la tabla FotoFiles, del Dataset ( try para el caso de q no se haya creado.)
            try { ds.Tables["fotoFiles"].Clear(); }
            catch { }

            // Cantidad de Controles en flPanel1 -- Las destruyo
            int n = flPanel1.Controls.Count;

            for (int i = 1; i <= n; i++)
            {
                flPanel1.Controls[0].Dispose();
            }


            Application.DoEvents();

            if (listView1.SelectedItems.Count != 0)
            {
                Cargar_Imagenes(listView1.SelectedItems[0].Name.ToString());                
            }
        }
        private void listView1_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e)
        {
           bd.Init();
           if (String.IsNullOrEmpty(e.Label) == false)
           {               
               bd.Execute("UPDATE cat_archivos SET NOMBRE = '" + e.Label + "' WHERE CATEGORIA = '" + listView1.SelectedItems[0].Name.ToString() + "';");
           }
        }
        
        private void btnSubirFoto_Click(object sender, EventArgs e)
        {                       

            if (listView1.SelectedItems.Count != 0)
            {

                // Captuar imagen y la sube a la bbdd            
                OpenFileDialog oFileDialog = new OpenFileDialog();

                oFileDialog.Filter = "jpg files (*.jpg)|*.jpg|png files (*.png)|*.png";
                oFileDialog.FilterIndex = 1;
                oFileDialog.RestoreDirectory = true;

                if (oFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (oFileDialog.FileName != null)
                    {
                        bd.Init();
                        int b = bd.addImage(oFileDialog.FileName, "salones_fotos", "file_data",listView1.SelectedItems[0].Name.ToString(), "0001000", strId);

                    }
                }                
            }
            else
            {
                MessageBox.Show("Seleccionar Primero una carpeta", "Falta Carpeta", MessageBoxButtons.OK);
            }                        
        }

        public string Id
        {
            get
            {
                return strId;
            }
            set
            {
                strId = value;
                if (strId != string.Empty)
                {
                    //Activamos.
                    flPanel1.Enabled = true;
                    tabControl1.Enabled = true;
                    Cargar_Carpetas();
                }
            }
        }

        
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            if (cTb > -1)
            {
                SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
                SaveFileDialog1.Filter = "JPG Image|*.jpg|Bitmap Image|*.bmp|PNG Image|*.png";
                SaveFileDialog1.Title = "Guardar Imagen";
                SaveFileDialog1.ShowDialog();

                if (SaveFileDialog1.FileName != "")
                {
                    // Cargo la Imagen Buffer//Stream
                    byte[] buffer;
                    System.IO.MemoryStream stream1;

                    buffer = bd.getImage(Convert.ToInt32(tB[cTb].Id), "salones_fotos");
                    stream1 = new System.IO.MemoryStream(buffer, true);
                    stream1.Write(buffer, 0, buffer.Length);

                    Image img;

                    // Cargamos la imagen en el Control Picture                    
                    //img. = System.Drawing.Bitmap.FromStream(stream1, true);
                    img = System.Drawing.Bitmap.FromStream(stream1, true);

                    img.Save(SaveFileDialog1.FileName);

                    img.Dispose();
                    stream1.Dispose();
                    img.Dispose();
                }
            }
        }

        private void btnCerrar_Click(object sender, EventArgs e)
        {
            // Destruimos tmpPic // La imagen maximizada, al destruirse desaparece...
            tmpPic.Dispose();
            btnCerrar.Visible = false;
        }

        private void btnImprimir_Click(object sender, EventArgs e)
        {                
            printDialog1.Document = printDocument1;

            if ((printDialog1.ShowDialog() == DialogResult.OK))
            {
                //printDocument1.PrintPage += new PrintPageEventHandler(this.OnPrintPage);
                printDocument1.Print();
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {

          // String textToPrint = "Imagen" + tB[cTb].Name;
          // Font printFont = new Font("Courier New", 12);
          
          // e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, 0, 0);
           
           Point mp = new Point(25,20);
           e.Graphics.DrawImage(tmpPic.Image, mp);
        }

        private void btnCerrarP_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

    }
}
